package com.shortchina.controller;

import com.alibaba.fastjson.JSON;
import com.shortchina.common.core.R;
import com.shortchina.model.vo.ShortUrlVo;
import com.shortchina.service.URLService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * URL控制器
 *
 * @author fc
 * @version 1.0
 * @data 2024/12/23 8:48 下午
 **/
@RestController
@RequestMapping("url")
public class URLController {
    private final static Logger logger = LoggerFactory.getLogger(URLController.class);


    @Resource
    private URLService urlService;
    @Value("${tshort.white_list:null}")
    private String whiteList;
    /**
     * 生成短链接
     * @param url
     * @param validTime 过期时间
     * @return
     */
    @RequestMapping("/generate")
    public R<Object> generate(String url, Long validTime) {
        if (StringUtils.isBlank(url)) {
            return R.failed("URL不能为空");
        }
        //白名单判定
        try {
            URL url1 = new URL(url);
            String domain = url1.getHost();
            String[] bmds = whiteList.split(",");
            for (String bmd : bmds) {
                if (bmd.startsWith(domain)) {
                    break;
                }else{
                    return R.failed("不在白名单内");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        ShortUrlVo dl= urlService.generate(url, validTime);
        logger.info("短链生成:{}", JSON.toJSONString(dl));
        return R.ok(dl);
    }
}
